package leetcode;

/**
 * @author niann
 * @description 合并两个有序链表
 * //TODO  https://leetcode.cn/problems/merge-two-sorted-lists/description/
 * @since 2024/10/24 19:48
 **/
public class LeetCode21 {


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode newList = new ListNode(-10086);
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                insertList(newList, list1.val);
                list1 = list1.next;
            } else {
                insertList(newList, list2.val);
                list2 = list2.next;
            }
        }
        if (list1 == null) {
            tailInsertLink(newList, list2);
        }
        if (list2 == null) {
            tailInsertLink(newList, list1);
        }
        return newList;
    }

    private void insertList(ListNode list, int value) {
        var flag = true;
        if (list.val == -10086) {
            list.val = value;
            flag = false;
        }
        while (list.next != null) {
            list = list.next;
        }
        if (flag) {
            list.next = new ListNode(value);
        }
    }

    private void tailInsertLink(ListNode source, ListNode target) {
        var cur = source;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = target;
    }
}
